package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.ScrollPane;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;

import database.DatabaseExtension;
import database.MyTransport;
import database.NewTirDataBase;
import database.MyShipment;

import enums.SearchType;

import Other.Glob;

public class AddShipment extends JFrame {
	
	private static AddShipment addShipmentInstance = null;
	private JPanel contentPane;
	private JTextField tfCode;
	private JTextField tfShipment;
	private JTextField tfDeparture;
	private JTextField tfLine;
	private JTable table;
	private JScrollPane scrollPane;
	//variable that represent this window frame
	private JFrame thisFrame = this;
	private DefaultTableModel model;
	//variable to enable and disable the screen
		boolean disable;


	/**
	 * Create the frame.
	 */
	private AddShipment() {
		setResizable(false);
		setTitle("Add Shipment to Transport");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 675, 378);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new LineBorder(new Color(0, 0, 0)));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
						.addComponent(panel_1, Alignment.LEADING, 0, 0, Short.MAX_VALUE)
						.addComponent(panel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE))
					.addContainerGap(40, Short.MAX_VALUE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
					.addComponent(panel, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
					.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 49, GroupLayout.PREFERRED_SIZE))
		);
		
		JLabel lblFRemoveShipment = new JLabel("F6 Remove Shipment");
		
		JLabel lblEscExit = new JLabel("Esc Exit");
		
		JLabel lblFReset = new JLabel("F7 Reset");
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGap(39)
					.addComponent(lblFRemoveShipment)
					.addPreferredGap(ComponentPlacement.RELATED, 263, Short.MAX_VALUE)
					.addComponent(lblEscExit)
					.addGap(37)
					.addComponent(lblFReset)
					.addGap(169))
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_1.createSequentialGroup()
					.addContainerGap(22, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblFRemoveShipment)
						.addComponent(lblEscExit)
						.addComponent(lblFReset))
					.addContainerGap())
		);
		panel_1.setLayout(gl_panel_1);
		
		JLabel lblTransport = new JLabel("Transport");
		
		JLabel lblNewLabel = new JLabel("Add Shipment");
		
		tfCode = new JTextField();
		tfCode.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a type is entered
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
				
					tfShipment.requestFocus();
					try {
						enterData();

					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					setModel();
					System.out.println("button is being pressed");
				}
			}
		});
		
		tfCode.getInputMap(tfCode.WHEN_FOCUSED)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "");
		tfCode.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 
				 //when textcode focused and f5 pressed search dialog comes up
				 Glob.type= SearchType.ADDSHIPMENTTRANSPORT;
				 
				search();
				
			    }
		});
		
		
		tfCode.setColumns(10);
		
		tfShipment = new JTextField();
		tfShipment.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a type is entered
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
				
				
					try {
						enterShipment();
						setModel();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					System.out.println("button is being pressed");
					tfShipment.setText(null);
				}
			}
		});
		tfShipment.getInputMap(tfShipment.WHEN_FOCUSED)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "");
		tfShipment.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 
				 //when textcode focused and f5 pressed search dialog comes up
				 Glob.type= SearchType.ADDSHIPMENTSHIPMENT;
				 
				 shipmentSearchOption();
				
			    }
		});
		
		tfShipment.setColumns(10);
		
		JButton sbCode = new JButton("F5 Search");
		sbCode.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 Glob.type = SearchType.ADDSHIPMENTTRANSPORT;
				 //when textcode focused and f5 pressed search dialog comes up
				 search();
			}
		});
		
		JButton sbShipment = new JButton("F5 Search");
		sbShipment.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				Glob.type = SearchType.ADDSHIPMENTSHIPMENT;
				 //when textcode focused and f5 pressed search dialog comes up
				shipmentSearchOption();
				
			}
		});
		
		tfDeparture = new JTextField();
		tfDeparture.setEditable(false);
		tfDeparture.getInputMap(tfDeparture.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "");
		tfDeparture.getActionMap().put("", new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				
					//escape from the screen
					if (disable == false){
						//escape from the screen
							escape();
						}
					
			}
		});
	
		tfDeparture.setColumns(10);
		
		tfLine = new JTextField();
		tfLine.setEditable(false);
		tfLine.getInputMap(tfLine.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), "");
		tfLine.getActionMap().put("", new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				//request focus in the goods code
				resetFields();
			}
		});
		tfLine.setColumns(10);
		
		JLabel lblDeparture = new JLabel("Departure:");
		lblDeparture.getInputMap(lblDeparture.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), "");
		lblDeparture.getActionMap().put("", new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				
				
				
				try {
					
				} catch (Exception e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				//remove item when F6 button pressed
				try {
					//NewTirDataBase c = (MyGood) DatabaseExtension.getTableID("SELECT * FROM good WHERE code = '" + tfCodeGoods.getText() +"' and ShipmentID = '"+ Shipment.getInstance().getFieldCode() +"'")[0];
					//NewTirDataBase c = (MyShipment) DatabaseExtension.getTableID("SELECT * FROM shipment WHERE transportID = '" + tfCode.getText() +"' and ShipmentID = '"+ tfShipment +"'")[0];
					

					DatabaseExtension.deleteShipmentInTransport(tfShipment.getText());
					setModel();
					tfShipment.setText(null);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		JLabel lblPackages = new JLabel("Line:");
		
		table = new JTable();
		scrollPane = new JScrollPane(table);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createSequentialGroup()
							.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
								.addComponent(lblNewLabel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(lblTransport, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE))
							.addGap(18)
							.addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
								.addComponent(tfShipment)
								.addComponent(tfCode, GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addComponent(sbShipment)
								.addComponent(sbCode))
							.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel.createSequentialGroup()
									.addGap(55)
									.addComponent(tfDeparture, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE)
									.addGap(18)
									.addComponent(tfLine, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel.createSequentialGroup()
									.addGap(85)
									.addComponent(lblDeparture)
									.addGap(92)
									.addComponent(lblPackages))))
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 630, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap(19, Short.MAX_VALUE)
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_panel.createSequentialGroup()
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblTransport)
								.addComponent(tfCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(sbCode))
							.addGap(18))
						.addGroup(gl_panel.createSequentialGroup()
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblDeparture)
								.addComponent(lblPackages))
							.addPreferredGap(ComponentPlacement.RELATED)))
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel)
						.addComponent(tfShipment, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(sbShipment)
						.addComponent(tfDeparture, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(tfLine, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 171, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel.setLayout(gl_panel);
		contentPane.setLayout(gl_contentPane);
	}
	
	//singleton
	public static AddShipment getInstance(){
		if(addShipmentInstance == null){
			addShipmentInstance = new AddShipment();
		}
		return addShipmentInstance;
		}
	
	public void setModel(){
		
		model = DatabaseExtension.buildTableModel("select shipment.shipmentID, client.client, addressee.addressee, SUM(good.parcel) as Packages, shipment.kilos, shipment.volume, shipment.invoice from shipment, good, client, addressee where shipment.addresseeID = addressee.addresseeID and shipment.clientID = client.clientID and shipment.shipmentID = good.shipmentID and shipment.transportID = '" + tfCode.getText() +"' group by shipment.shipmentID");
		System.out.println("This is the model size " + model.getColumnCount());
		table.setModel(model);
		//DatabaseExtension.getTableID("SELECT * FROM Good WHERE ShipmentID = '" + s.getFieldCode() +"'");
		//DatabaseExtension.printQueryArea("SELECT * FROM Good WHERE ShipmentID = '" + s.getFieldCode() +"'", northArea);
	}

	public void escape(){
		thisFrame.dispose();
		Menu.getInstance().enableMenu();
	}
	
	public void initTransport(MyTransport transport){
		
		tfCode.setText(transport.getTransportID());
		tfDeparture.setText(transport.getDeparture());
		tfLine.setText(transport.getCountryName());
		
	}
	
	public void initShipment(MyShipment shipment){
		
		tfShipment.setText(shipment.getShipmentID());
	}
	
	public void enterShipment() throws Exception{
		
		
		ScreenHandling.checkID(tfShipment);
		
		
		ScreenHandling.checkIdStringOnTable(tfCode, SearchType.TRANSPORT);
		ScreenHandling.checkIdOnTable(tfShipment, SearchType.SHIPMENT);
		
		DatabaseExtension.insertShipment(tfCode.getText(),tfShipment.getText());
		
		
	}
	
	public void enterData()throws Exception{
		
		Glob.setType(SearchType.ADDSHIPMENTTRANSPORT);
		ScreenHandling.checkIDString(tfCode);
		ScreenHandling.checkIdStringOnTable(tfCode, SearchType.TRANSPORT);
		
		try{
			
		NewTirDataBase c = (MyTransport) DatabaseExtension.getTableID("SELECT * FROM transport WHERE transportID = '" + tfCode.getText() +"'")[0];
		
		tfDeparture.setText(((MyTransport) c).getDeparture());
		tfLine.setText(((MyTransport) c).getCountryName());
		}catch(NumberFormatException exception){
			tfCode.setText(null);
			System.out.println("This is the exception release when there is an String");
			exception.printStackTrace();
		}catch(Exception exception){
			System.out.println("General Exception");
			exception.printStackTrace();
		}
		
	}
	
	public void resetFields(){
		
		
		tfCode.setText(null);
		tfShipment.setText(null);
		tfDeparture.setText(null);
		tfLine.setText(null);
		tfCode.requestFocus();
		model = new DefaultTableModel();
		table.setModel(model);
		
	
	
		
		
	}
	
	public void checkIDs(){
		
		
		
		/**
		try {
			ScreenHandling.checkIDString(tfCode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList <Integer>ids = DatabaseExtension.columnIDs("select * from shipment where transportID = '"+ tfCode +"'");
		boolean ok = false;
	
			for (int iterate: ids) {
				if (iterate == Integer.parseInt(tfShipment.getText()))
						ok=true;
				System.out.println(ids);
			}
			if (!ok) {
				JOptionPane.showMessageDialog(null, "Choose an ID from the table");
				tfShipment.setText("");
				return;
			}
		
		*/
		
	}
	
	public void search(){
		
		SearchWindow s = SearchWindow.getInstance();
		s.setTitle();
		s.setVisible(true);
		disableAddShipment();
	}
	
	public void shipmentSearchOption(){
		Glob.setType(SearchType.ADDSHIPMENTSHIPMENT);
		ShipmentSearchOption ship = ShipmentSearchOption.getInstance();
		ship.setVisible(true);
		disableAddShipment();
	}
	
	//method to disable the screen
	public void disableAddShipment(){
		AddShipment.getInstance().disable();
		disable = true;
	}
	
	//method to enable the screen
			public void enableAddShipment(){
				AddShipment.getInstance().enable();
				disable = false;
				if (Glob.type ==  SearchType.ADDSHIPMENTTRANSPORT){
					tfCode.requestFocus();
				}else if (Glob.type ==  SearchType.ADDSHIPMENTSHIPMENT){
					tfShipment.requestFocus();
				}
				
				AddShipment.getInstance().toFront();
			}
			//method to get the disable boolean
			public boolean getDisable(){
				return disable;
			}
}
